package com.sunlee.admin.api.module.job.task;

import com.qianxinyao.analysis.jieba.keyword.Keyword;
import com.qianxinyao.analysis.jieba.keyword.TFIDFAnalyzer;
import com.sunlee.common.core.constant.Constant;
import com.sunlee.common.service.entity.ThirdProductEntity;
import com.sunlee.common.service.service.ThirdProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 该类已废弃
 * PPT标题解析分词为分类
 *
 * @author sunulee
 */
@Deprecated
@Component("analysisPptCategory")
public class AnalysisPptCategoryTask implements ITask {

    @Autowired
    private ThirdProductService thirdProductService;

    public static final String FILTER_REGEX = "[\n\r\t`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？^p]";
    public static final List<String> FILTER_TAG = new ArrayList<>();


    static {
        FILTER_TAG.add("主题");
        FILTER_TAG.add("演示");
        FILTER_TAG.add("PowerPoint");
        FILTER_TAG.add("背景");
    }

    @Override
    public void run(String params) {
        List<ThirdProductEntity> list = thirdProductService.list();


        TFIDFAnalyzer tfidfAnalyzer = new TFIDFAnalyzer();

        int total = 0;
        List<ThirdProductEntity> updateList = new ArrayList<>();

        for (ThirdProductEntity fileInfo : list) {
            total++;

            String title = fileInfo.getTitle();
            String tag = fileInfo.getTag();

            // 1、过滤特殊字符
            title = title.replaceAll(FILTER_REGEX, "").replaceAll("　", "").replaceAll(" ", "");

            // 2、解析分词，并搜集关键字，最多只获取8个标签
            List<Keyword> analysisKeyword = tfidfAnalyzer.analyze(title, 8);
            Set<String> tagsSet = analysisKeyword.stream().map(Keyword::getName).collect(Collectors.toCollection(LinkedHashSet::new));

            // 3、取标签值，并add进集合
            if (StringUtils.isNotBlank(tag)) {
                tagsSet.addAll(Arrays.asList(tag.trim().split(Constant.SYMBOL_SLASH)));
            }

            // 4、过滤多余标签
            filterTag(tagsSet);

            // 5、更新标签
            fileInfo.setTag(String.join(Constant.SYMBOL_SLASH, tagsSet));
            System.out.println(fileInfo.getTag());

            updateList.add(fileInfo);
            if (total == 1000) {
                thirdProductService.updateBatchById(updateList);
                total = 0;
                updateList.clear();
            }
        }
    }

    private void filterTag(Set<String> allTag) {
        FILTER_TAG.forEach(allTag::remove);

        if (CollectionUtils.isEmpty(allTag)) {
            return;
        }

        allTag.removeIf(str -> str.length() == 1);
    }
}
